﻿namespace Frameworks
{
    internal class FpsCounter
    {
        private float _currentFps;
        private float _updateInterval;
        private int _frames;
        private float _accumulator;
        private float _timeLeft;

        public FpsCounter()
        {
            SetUpdateInterval(0.5f);
        }

        public FpsCounter(float updateInterval)
        {
            SetUpdateInterval(updateInterval);
        }

        public void SetUpdateInterval(float updateInterval)
        {
            _updateInterval = updateInterval <= 0 ? 0.5f : updateInterval;
            Reset();
        }

        public string CurrentFps
        {
            get { return _currentFps.ToString("F2"); }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="elapseSeconds">逻辑流逝时间，以秒为单位</param>
        /// <param name="realElapseSeconds">真实流逝时间，以秒为单位</param>
        public void Update(float elapseSeconds, float realElapseSeconds)
        {
            _frames++;
            _accumulator += realElapseSeconds;
            _timeLeft -= realElapseSeconds;

            if (_timeLeft <= 0f)
            {
                _currentFps = _accumulator > 0f ? _frames / _accumulator : 0f;
                _frames = 0;
                _accumulator = 0f;
                _timeLeft += _updateInterval;
            }
        }

        private void Reset()
        {
            _currentFps = 0f;
            _frames = 0;
            _accumulator = 0f;
            _timeLeft = 0f;
        }
    }
}
